import win32com.client
import time
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def initialize_canoe(configuration_path, visible=True):
    """
    初始化CANoe应用并加载配置文件。
    :param configuration_path: CANoe配置文件路径
    :param visible: 是否显示CANoe界面，默认为True
    :return: CANoe应用实例
    """
    try:
        canoe_app = win32com.client.Dispatch("CANoe.Application")
        canoe_app.Visible = visible
        canoe_app.Open(configuration_path)
        visibility_status = "visible" if visible else "hidden"
        logging.info(f"CANoe initialized and configuration loaded: {configuration_path}. CANoe interface is {visibility_status}.")
        return canoe_app
    except FileNotFoundError:
        logging.error(f"Configuration file not found: {configuration_path}")
        raise
    except Exception as e:
        logging.error(f"Failed to initialize CANoe or load configuration file: {configuration_path}. Error: {e}")
        raise

def start_measurement(canoe_app, wait_time=2):
    """
    启动CANoe测量。
    :param canoe_app: CANoe应用实例
    :param wait_time: 测量启动后的等待时间（秒），默认为2秒
    """
    try:
        if not canoe_app.Measurement.IsRunning:
            canoe_app.Measurement.Start()
            logging.info("CANoe measurement started.")
            time.sleep(wait_time)
        else:
            logging.warning("CANoe measurement is already running.")
    except Exception as e:
        logging.error(f"Failed to start CANoe measurement. Error: {e}")
        raise

def read_signals(canoe_app, signal_names):
    """
    读取指定信号的值。
    :param canoe_app: CANoe应用实例
    :param signal_names: 信号名称列表
    :return: 信号值字典
    """
    if not signal_names:
        logging.warning("No signal names provided. Returning empty dictionary.")
        return {}

    signal_values = {}
    for signal_name in signal_names:
        try:
            signal = canoe_app.Configuration.Networks.Item(1).Simulation.NetworkVariables.Item(signal_name)
            signal_value = signal.Value
            signal_values[signal_name] = signal_value
            logging.info(f"Signal: {signal_name}, Value: {signal_value}")
        except KeyError:
            logging.error(f"Signal '{signal_name}' not found in the CANoe configuration.")
        except Exception as e:
            logging.error(f"Error reading signal {signal_name}: {e}")
    return signal_values

def stop_measurement(canoe_app):
    """
    停止CANoe测量。
    :param canoe_app: CANoe应用实例
    """
    try:
        if canoe_app.Measurement.IsRunning:
            canoe_app.Measurement.Stop()
            logging.info("CANoe measurement stopped.")
        else:
            logging.warning("CANoe measurement is not running.")
    except Exception as e:
        logging.error(f"Failed to stop CANoe measurement. Error: {e}")
        raise

def close_canoe(canoe_app):
    """
    关闭CANoe应用。
    :param canoe_app: CANoe应用实例
    """
    try:
        if canoe_app.Visible:
            logging.info("Closing CANoe application.")
            canoe_app.Quit()
        else:
            logging.warning("CANoe application is already closed or not visible.")
    except Exception as e:
        logging.error(f"Failed to close CANoe application. Error: {e}")
        raise